package com.gameplatform.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gameplatform.model.User;
import com.gameplatform.service.UserService;
import com.gameplatform.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {
    private UserService userService = new UserService();
    private ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo == null || pathInfo.equals("/")) {
            // 获取所有用户
            List<User> users = userService.getAllUsers();
            ResponseUtil.writeResponse(response, 200, "success", users);
        } else if (pathInfo.startsWith("/")) {
            String[] parts = pathInfo.split("/");
            if (parts.length == 2) {
                try {
                    int userId = Integer.parseInt(parts[1]);
                    User user = userService.getUserById(userId);
                    if (user != null) {
                        ResponseUtil.writeResponse(response, 200, "success", user);
                    } else {
                        ResponseUtil.writeResponse(response, 404, "User not found", null);
                    }
                } catch (NumberFormatException e) {
                    ResponseUtil.writeResponse(response, 400, "Invalid user ID", null);
                }
            }
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo != null && pathInfo.equals("/register")) {
            // 用户注册
            User user = objectMapper.readValue(request.getInputStream(), User.class);
            
            if (userService.getUserByUsername(user.getUsername()) != null) {
                ResponseUtil.writeResponse(response, 400, "Username already exists", null);
                return;
            }
            
            user.setRole("user");
            boolean success = userService.createUser(user);
            
            if (success) {
                ResponseUtil.writeResponse(response, 201, "User registered successfully", user);
            } else {
                ResponseUtil.writeResponse(response, 500, "Failed to register user", null);
            }
        } else if (pathInfo != null && pathInfo.equals("/login")) {
            // 用户登录
            Map<String, String> loginData = objectMapper.readValue(request.getInputStream(), Map.class);
            String username = loginData.get("username");
            String password = loginData.get("password");
            
            User user = userService.login(username, password);
            if (user != null) {
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("user", user);
                responseData.put("token", session.getId());
                
                ResponseUtil.writeResponse(response, 200, "Login successful", responseData);
            } else {
                ResponseUtil.writeResponse(response, 401, "Invalid username or password", null);
            }
        } else {
            // 创建新用户
            User user = objectMapper.readValue(request.getInputStream(), User.class);
            boolean success = userService.createUser(user);
            
            if (success) {
                ResponseUtil.writeResponse(response, 201, "User created successfully", user);
            } else {
                ResponseUtil.writeResponse(response, 500, "Failed to create user", null);
            }
        }
    }
    
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo != null && pathInfo.startsWith("/")) {
            String[] parts = pathInfo.split("/");
            if (parts.length == 2) {
                try {
                    int userId = Integer.parseInt(parts[1]);
                    User user = objectMapper.readValue(request.getInputStream(), User.class);
                    user.setId(userId);
                    
                    // 检查是否是管理员操作（包含role字段）
                    boolean success;
                    if (user.getRole() != null) {
//                        success = userService.updateUserWithRole(user);
                        success = userService.updateUser(user);
                    } else {
                        success = userService.updateUser(user);
                    }
                    
                    if (success) {
                        ResponseUtil.writeResponse(response, 200, "User updated successfully", user);
                    } else {
                        ResponseUtil.writeResponse(response, 500, "Failed to update user", null);
                    }
                } catch (NumberFormatException e) {
                    ResponseUtil.writeResponse(response, 400, "Invalid user ID", null);
                }
            }
        }
    }
    
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo != null && pathInfo.startsWith("/")) {
            String[] parts = pathInfo.split("/");
            if (parts.length == 2) {
                try {
                    int userId = Integer.parseInt(parts[1]);
                    boolean success = userService.deleteUser(userId);
                    
                    if (success) {
                        ResponseUtil.writeResponse(response, 200, "User deleted successfully", null);
                    } else {
                        ResponseUtil.writeResponse(response, 500, "Failed to delete user", null);
                    }
                } catch (NumberFormatException e) {
                    ResponseUtil.writeResponse(response, 400, "Invalid user ID", null);
                }
            }
        }
    }
}